package com.yonyou.pmclouds.project.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessorWithField;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.project.entity.ProjectConst;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;

public class ProjectEndCheck implements SingleProcessorWithField<ProjectVO> {
    private static final String[] FIELDS = new String[]{ProjectVO.PROJECT_STATE};
    private String operator;

    public ProjectEndCheck(String operator) {
        this.operator = operator;
    }

    @Override
    public void process(ProjectVO vo, ProjectVO orig) throws BusinessException {
        if (orig.getProjectState() == ProjectConst.STATE_END) {
            throw new BusinessException("项目已经终止，不可再次终止！");
        }
        if (!StringUtils.equals(orig.getManager(), operator)) {
            throw new BusinessException("只有该项目的项目经理才可以终止该项目！");
        }
        Date endDate = vo.getEndDate();
        Date startDate = orig.getApprovalDate();
        if (!DateUtils.isSameDay(endDate, startDate) && endDate.before(startDate)) {
            throw new BusinessException("项目结束日期不可晚于立项日期!");
        }
        vo.setProjectState(ProjectConst.STATE_END);
    }

    @Override
    public String[] getChangedField() {
        return FIELDS;
    }
}
